package zhuzx.report;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zhuzx.util.*;

public class BackupReportProcessor {
	
	private static final AbstractConsumerQueue<Map<String,String>> queue = new AbstractFifoConsumerQueue<Map<String,String>>(100) {
		protected void process(Map<String,String> data) {
			System.out.println(processData(data));
		}
	};
	
	public static String pushIntoQueue(Map<String,String> data) {
		return queue.pushIntoQueue(data) ? ("稍后将为您发送到邮箱" + data.get("email_addr")) : "任务队列已满";
	}
	
	private static String processData(Map<String,String> data) {
		String target = data.remove("email_addr");
		String bodyStr = data.remove("bodyData");
		Map<String,String> bodyData = parseBodyString(bodyStr);
		Map<String,String> formData = WebUtil.createMapFromJson(bodyData.get("formData"));
		Map<String,String> urlData = WebUtil.createMapFromJson(bodyData.get("urlData"));
		String remoteResultStr = null;
		try {
			remoteResultStr = urlData.get("queryMethod").equalsIgnoreCase("GET") ? 
					NetUtil.get(urlData.get("queryUrl"), formData, data) :
					NetUtil.postInputStream(urlData.get("queryUrl"), formData, data, null, null);
		} catch (IOException e) {
			throw new RuntimeException("远程查询调用失败", e);
		}
		String rowsStr = WebUtil.createMapFromJson(remoteResultStr).get("rows");
		List<Map<String,String>> list = WebUtil.createListMapFromJsonArray(rowsStr);
		String fileName = JavaScriptResolver.getNameByUrl(urlData.get("pageUrl"));
		if (list.size() == 0) return "[" + fileName + "]" + "查询无数据，不发送邮件。";
		list = JavaScriptResolver.convertResultSet(list, bodyData.get("pageCode"), bodyData.get("columnsCode"));
		byte[] bytes = ExcelUtil.createExcel(true, null, null, list);
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		try {
			BackupRcExportExcel.sendEmail(target, fileName, "本邮件由系统自动发送，请勿回复。", fileName+".xlsx", in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "[" + fileName + "]" + "已发送至" + target;
	}
	
	private static Map<String,String> parseBodyString(String bodyData) {
		String[] datas = MicroUtil.splitByStringAutoEscape(bodyData, TextConstants.HTTP_ENTITY_SEPARATOR);
		Map<String, String> map = new HashMap<>();
		for (String string : datas) {
			int index = string.indexOf(':');
			map.put(string.substring(0, index), string.substring(index+1));
		}
		return map;
	}

}